import Mock from 'mockjs' // 导入 mockjs
import {useSysUserStore} from '../stores/user.ts'
const useSysUser = useSysUserStore()

// 定义用户数据
Mock.mock('/api/login', 'post', (options) => {
    // 1. 正确解析请求体
    const user = JSON.parse(options.body);
    const { username, password } = user;

    console.log('Mock 收到登录请求:', user);
    const foundUser = useSysUser.login(username, password);
    console.log('Mock 登录结果:', foundUser)

    if (foundUser) {
        return {
            code: 200,
            msg: '登录成功', // 直接使用 msg 字段
            data: {
                id: foundUser.id,
                router: foundUser.router,
                token: foundUser.token,
                username: foundUser.username,
                // password: foundUser.password,
                name: foundUser.name,
                age: foundUser.age,
                gender: foundUser.gender,
                createTime: foundUser.createTime,
                updateTime: foundUser.updateTime,
                imgUrl: foundUser.imgUrl,
                studengOrteacherId: foundUser.studengOrteacherId,
            },
        };
    } else {
        return {
            code: 401, // 使用更标准的 401 未授权状态码
            msg: '用户名或密码错误', // 直接使用 msg 字段
            data: null, // 失败时 data 为 null
        };
    }
});

// 根据id查找 用户
Mock.mock(/\/api\/selectIdAndData\?id=\d+/, 'get', (options) => {
    // 1. 获取请求的完整 URL
    const url = options.url;

    // 2. 解析 URL 参数
    const query = url.split('?')[1]; // 获取 "id103"
    const id = Number(query.split('=')[1]);  // 获取 "103"
    console.log('Mock 获取的 id:', id)

    // 3. 使用 find 查找匹配的用户
    const user = useSysUser.sysUser.find((user) => {
        return user.studengOrteacherId === id;
    });

    // 4. 判断是否找到用户
    if (user) {
        console.log('Mock 获取的 user:', user);
        return {
            code: 200,
            msg: '查询成功',
            data: user, // 直接返回用户对象
        };
    } else {
        // 5. 如果没有找到，返回错误信息
        return {
            code: 404,
            msg: '用户不存在',
            data: null,
        };
    }
})

// 获取学生用户信息
Mock.mock('/api/allUserData', 'post', (options) => {
    const users = JSON.parse(options.body);
    const addStudentData = computed(() => useSysUser.findUsersByConditions( users)).value
    console.log('Mock 获取的 users:', addStudentData)

    const selectList = []
    addStudentData.forEach(user => {
        selectList.push({
            id: user.studengOrteacherId,
            name: user.name,
        })
    })

    return {
        code: 200,
        msg: '查询成功',
        data: selectList,
    };
})

